package com.rongkang.interview.juc.deadLock;

import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @author: 荣康
 * @date: 2021/12/14
 * 死锁是什么：死锁是指两个或者两个以上的进程在执行过程中，因为争夺资源而造成一种互相等待的现象,若没有外力干涉他们都等待无法推进下去
 * 怎么导致的：
 *              1.系统资源不足
 *              2.进程运行推进的顺序不合适
 *              3.资源分配不当
 * 怎么排查：
 * 写个demo：
 */

class HoldLockThread implements Runnable {
    private String lockA;
    private String lockB;

    public HoldLockThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA) {
            System.out.println(Thread.currentThread().getName()+"\t 自己持有" + lockA + "\t 尝试获得" + lockB);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName()+"\t自己持有" + lockB + "\t 尝试获得" + lockA);
            }
        }
    }
}

public class DeadLockDemo {
    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";
        new Thread(new HoldLockThread(lockA, lockB), "lockAAAA").start();
        new Thread(new HoldLockThread(lockB, lockA), "lockBBBB").start();

    }
}
